<template>
  <a-modal
    :open="props.modelVisible"
    title="课程管理"
    :destroyOnClose="true"
    @cancel="handleCancel"
    @ok="handleOk"
    width="710px"
  >
    <div class="container">
      <div style="width: 45%">
        <a-input-group compact style="margin-top: 10px">
          <a-select style="width: 30%" v-model:value="selectType">
            <a-select-option value="名称">名称</a-select-option>
            <a-select-option value="课程号">课程号</a-select-option>
          </a-select>
          <a-input-search
            placeholder="搜索课程"
            style="width: 70%"
            v-model:value="selectInput"
            @search="findCourse"
            enter-button
          />
        </a-input-group>
        <a-divider></a-divider>

        <a-list 
          style="height: 73%; overflow-y: auto; margin-top: 10px" 
          :data-source="unSelectData"
          :loading="spinning"
        >
          <template #empty>
            <div style="text-align: center; padding: 20px;">
              <p>没有找到课程</p>
              <p v-if="!selectInput">请输入关键字搜索课程</p>
            </div>
          </template>
          <template #renderItem="{ item }">
            <a-list-item class="item" @click="selectItem(item)" :key="item.courseId">
              <span style="width: 70%"> {{ item.courseName }}</span>
              <template #actions>
                <CheckOutlined
                  style="color: rgb(102 152 255)"
                  v-if="selectedDate.some((obj) => obj.courseId === item.courseId)"
                />
              </template>
            </a-list-item>
          </template>
        </a-list>
      </div>
      <a-divider type="vertical" style="height: 100%" />
      <div style="width: 45%">
        <div style="margin-top: 10px">已选择课程 · {{ selectedDate.length }}</div>
        <a-list style="height: 85%; overflow-y: auto; margin-top: 10px" :data-source="selectedDate">
          <template #empty>
            <div style="text-align: center; padding: 20px;">
              <p>未选择任何课程</p>
              <p>从左侧列表选择要关联的课程</p>
            </div>
          </template>
          <template #renderItem="{ item }">
            <a-list-item class="item">
              <span> {{ item.courseName }}</span>
              <template #actions>
                <CloseOutlined class="deleteIcon" @click="deleteItem(item.courseId)" />
              </template>
            </a-list-item>
          </template>
        </a-list>
      </div>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
import UserDao from '@/daos/user_dao';
import CourseDao from '@/daos/course_dao';
import ProjecrDao from '@/daos/project_dao';
import { message } from 'ant-design-vue';
import { useStore } from 'vuex';
import { CheckOutlined, CloseOutlined } from '@ant-design/icons-vue';

const projectDao = new ProjecrDao();
const store = useStore();
const courseDao = new CourseDao();
const userDao = new UserDao();

interface Course {
  courseId: number;
  courseName: string;
}

const props = defineProps({
  modelVisible: {
    type: Boolean,
    default: false
  },
  courseList: {
    type: Array as () => Course[],
    default: () => []
  }
});

const emit = defineEmits(['update:modelVisible', 'confirm']);

// 搜索相关
const selectType = ref('名称');
const selectInput = ref('');

// 加载状态
const spinning = ref<boolean>(false);

// 课程列表
const unSelectData = ref<Course[]>([]);
const selectedDate = ref<Course[]>([]);

// 组件加载时初始化
onMounted(() => {
  if (props.modelVisible) {
    findCourse();
    initSelectedCourses();
  }
});

// 监听模态框显示状态变化
watch(
  () => props.modelVisible,
  (newValue) => {
    if (newValue) {
      findCourse();
      initSelectedCourses();
    }
  }
);

// 初始化已选择的课程
const initSelectedCourses = () => {
  if (props.courseList && props.courseList.length > 0) {
    selectedDate.value = props.courseList.map((item) => ({ ...item }));
  } else {
    selectedDate.value = [];
  }
};

// 查询课程
const findCourse = async () => {
  spinning.value = true;
  try {
    let result;
    if (selectType.value === '课程号') {
      // 转换为数字
      const courseId = selectInput.value ? Number(selectInput.value) : null;
      result = await courseDao.findCourse(courseId, null);
    } else {
      result = await courseDao.findCourse(null, selectInput.value);
    }

    if (result.data.code === 200) {
      unSelectData.value = result.data.data || [];
      
      // 过滤掉已选择的课程
      if (selectedDate.value.length > 0) {
        const selectedIds = selectedDate.value.map(item => item.courseId);
        unSelectData.value = unSelectData.value.filter(item => !selectedIds.includes(item.courseId));
      }
    } else {
      message.error('获取课程列表失败');
    }
  } catch (error) {
    console.error('查询课程失败:', error);
    message.error('查询课程失败');
  } finally {
    spinning.value = false;
  }
};

// 选择课程
const selectItem = (newItem) => {
  let index = selectedDate.value.findIndex((item) => item.courseId === newItem.courseId);
  if (index === -1) {
    selectedDate.value.push(newItem);
    // 从未选择列表中移除
    unSelectData.value = unSelectData.value.filter(item => item.courseId !== newItem.courseId);
  } else {
    selectedDate.value.splice(index, 1);
    // 添加回未选择列表
    unSelectData.value.push(newItem);
  }
};

// 删除已选择的课程
const deleteItem = (courseId) => {
  const index = selectedDate.value.findIndex((item) => item.courseId === courseId);
  if (index !== -1) {
    const removedItem = selectedDate.value[index];
    selectedDate.value.splice(index, 1);
    // 添加回未选择列表
    unSelectData.value.push(removedItem);
  }
};

// 取消
const handleCancel = () => {
  emit('update:modelVisible', false);
};

// 确定
const handleOk = async () => {
  try {
    const result = await projectDao.upsertDeleteCourses(store.getters.projectId, selectedDate.value);
    if (result.data.code === 200) {
      message.success(result.data.data);
      emit('confirm');
      emit('update:modelVisible', false);
    } else {
      message.error(result.data.data || '更新课程关联失败');
    }
  } catch (error) {
    console.error('更新课程关联失败:', error);
    message.error('更新课程关联失败');
  }
};
</script>
<style lang="scss" scoped>
.container {
  display: flex;
  justify-content: space-around;
  width: 100%;
  height: 440px;
}

.item {
  display: flex;
  justify-content: space-between;
}

.item:hover {
  cursor: pointer;
  background-color: #f5f5f5aa;
}

.deleteIcon:hover {
  color: red;
}
</style>
